package com.artron.mediaartron.ui.fragment.center;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.artron.baselib.base.BaseStaticFragment;
import com.artron.baselib.entity.Response;
import com.artron.baselib.image.ImageUtils;
import com.artron.mediaartron.R;
import com.artron.mediaartron.data.config.AppProfile;
import com.artron.mediaartron.data.entity.LoginData;
import com.artron.mediaartron.data.entity.User;
import com.artron.mediaartron.data.net.NetConstant;
import com.artron.mediaartron.data.net.RetrofitHelper;
import com.artron.mediaartron.ui.activity.GeneralActivity;
import com.artron.mediaartron.ui.activity.MainActivity;
import com.artron.mediaartron.ui.callback.MainActivityCallback;
import com.artron.mediaartron.ui.helper.ThrottleFirstClickHelper;
import com.umeng.socialize.bean.SHARE_MEDIA;

import butterknife.BindView;
import retrofit2.http.HEAD;
import rx.Observable;
import rx.functions.Action0;
import rx.functions.Action1;

import static android.app.Activity.RESULT_OK;

/**
 * Class description here
 *
 * @author doing
 * @version 1.0.0
 * @since 2017-11-10.
 */

public class SettingFragment extends BaseStaticFragment implements
        View.OnClickListener, MainActivityCallback {


    @BindView(R.id.SettingFragment_tv_userdata)
    protected TextView mTvUserdata;
    @BindView(R.id.SettingFragment_iv_user_icon)
    protected ImageView mIvUserIcon;
    @BindView(R.id.SettingFragment_tv_manager)
    protected TextView mTvManager;
    @BindView(R.id.SettingFragment_tv_help)
    protected TextView mTvHelp;
    @BindView(R.id.SettingFragment_tv_about)
    protected TextView mTvAbout;
    @BindView(R.id.SettingFragment_tv_logout)
    protected TextView mTvLogout;
    @BindView(R.id.SettingFragment_tv_code)
    protected TextView mTvCode;
    private LoginData mLoginData;
    private Intent mIntent;

    public static SettingFragment newInstance(LoginData loginData) {
        SettingFragment fragment = new SettingFragment();
        fragment.init(loginData);
        return fragment;
    }

    private void init(LoginData loginData) {
        this.mLoginData = loginData;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_setting;
    }

    @Override
    protected void initView() {
        try {
            PackageManager manager = getActivity().getPackageManager();
            PackageInfo info = manager.getPackageInfo(getActivity().getPackageName(), 0);
            String version = info.versionName;
            mTvCode.setText("V" + version);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        ThrottleFirstClickHelper.throttleFirst(mTvUserdata, this);
        ThrottleFirstClickHelper.throttleFirst(mTvManager, this);
        ThrottleFirstClickHelper.throttleFirst(mTvHelp, this);
        ThrottleFirstClickHelper.throttleFirst(mTvAbout, this);
        ThrottleFirstClickHelper.throttleFirst(mTvLogout, this);

        if (!AppProfile.getUserInfo().isLogin()) {
            mTvLogout.setVisibility(View.GONE);
        } else {
            if (mLoginData != null) {
                mIvUserIcon.setVisibility(View.VISIBLE);
                ImageUtils.setCircleUrl(mIvUserIcon, mLoginData.getPhotoUrl());
            } else {
                mIvUserIcon.setVisibility(View.GONE);
            }
        }
    }



    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.SettingFragment_tv_userdata:
                AppProfile.getUserInfo().startLoginActivity(mContext, new Action0() {
                    @Override
                    public void call() {
                        GeneralActivity.startForResult(mContext, GeneralActivity.USER_INFO,
                                "个人资料", mLoginData);
                    }
                });
                break;
            case R.id.SettingFragment_tv_manager:
                AppProfile.getUserInfo().startLoginActivity(mContext, new Action0() {
                    @Override
                    public void call() {
                        GeneralActivity.start(mContext, GeneralActivity.ACCOUNT_MANAGE,
                                "账号管理", mLoginData);
                    }
                });
                break;
            case R.id.SettingFragment_tv_help:
                GeneralActivity.start(mContext, GeneralActivity.HELP_LIST, "使用帮助");
                break;
            case R.id.SettingFragment_tv_about:
                GeneralActivity.start(mContext, GeneralActivity.HELP, "关于", NetConstant.HELP_ABOUT);
                break;
            case R.id.SettingFragment_tv_logout:
                AppProfile.getUserInfo().startLoginActivity(mContext, new Action0() {
                    @Override
                    public void call() {
                        User user = AppProfile.getUserInfo().getUser();
                        if (TextUtils.isEmpty(user.getLoginPlatform())) {
                            AppProfile.getUserInfo().logout();
                        } else {
                            String loginPlatform = user.getLoginPlatform();
                            if ("qq".equals(loginPlatform)) {
                                AppProfile.getUserInfo().logoutPlatform(getActivity(), SHARE_MEDIA.QQ);
                            } else if ("sina".equals(loginPlatform)) {
                                AppProfile.getUserInfo().logoutPlatform(getActivity(), SHARE_MEDIA.SINA);
                            } else {
                                AppProfile.getUserInfo().logoutPlatform(getActivity(), SHARE_MEDIA.WEIXIN);
                            }
                        }
                        mTvLogout.setVisibility(View.GONE);
                        mIvUserIcon.setVisibility(View.INVISIBLE);
                    }
                });
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != MainActivity.RESULT_OK) {
            return;
        }

        switch (requestCode) {
            case GeneralActivity.REQUEST_CODE:
                this.mIntent = data;
                String name = data.getStringExtra(UserInfoFragment.USER_NAME);
                String profile = data.getStringExtra(UserInfoFragment.PERSONALIZED);
                String iconPath = data.getStringExtra(UserInfoFragment.USER_ICON);
                String gender = data.getStringExtra(UserInfoFragment.GENDER);
                String birthday = data.getStringExtra(UserInfoFragment.BIRTHDAY);
                String city = data.getStringExtra(UserInfoFragment.CITY);
                isRun(name, new Action1<String>() {
                    @Override
                    public void call(String s) {
                        mLoginData.setNickname(s);
                    }
                });
                isRun(profile, new Action1<String>() {
                    @Override
                    public void call(String s) {
                        mLoginData.setSignature(s);
                    }
                });
                isRun(iconPath, new Action1<String>() {
                    @Override
                    public void call(String s) {
                        ImageUtils.setCircleUrl(mIvUserIcon, s);
                        mLoginData.setPhotoUrl(s);
                    }
                });
                isRun(gender, new Action1<String>() {
                    @Override
                    public void call(String s) {
                        mLoginData.setSex(s);
                    }
                });
                isRun(birthday, new Action1<String>() {
                    @Override
                    public void call(String s) {
                        mLoginData.setBirthday(s);
                    }
                });
                if (city.contains("-")) {
                    String[] addressArr = city.split("-");
                    if (addressArr.length == 3) {
                        isRun(addressArr[0], new Action1<String>() {
                            @Override
                            public void call(String s) {
                                mLoginData.setProvinceName(s);
                            }
                        });
                        isRun(addressArr[1], new Action1<String>() {
                            @Override
                            public void call(String s) {
                                mLoginData.setCityName(s);
                            }
                        });
                        isRun(addressArr[2], new Action1<String>() {
                            @Override
                            public void call(String s) {
                                mLoginData.setCountyName(s);
                            }
                        });
                    }
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void isRun(String text, Action1<String> action) {
        if (!TextUtils.isEmpty(text)) {
            action.call(text);
        }
    }

    @Override
    public boolean onBackPressed() {
        if (mIntent != null) {
            getActivity().setResult(RESULT_OK, mIntent);
        }
        return super.onBackPressed();
    }

    @Override
    public void refreshData() {
        boolean isLogin = AppProfile.getUserInfo().isLogin();
        if (isLogin) {
            int visibility = mIvUserIcon.getVisibility();
            if (visibility == View.INVISIBLE) {
                String passId = AppProfile.getUserInfo().getPassId();
                Observable<Response<LoginData>> api = RetrofitHelper.getLoginApi().getUserInfo(passId);
                RetrofitHelper.subscript(api, new Action1<Response<LoginData>>() {
                    @Override
                    public void call(Response<LoginData> response) {
                        if (response != null && "OK".equals(response.getStatus())
                                && response.getData() != null) {
                            mLoginData = response.getData();
                            ImageUtils.setCircleUrl(mIvUserIcon, mLoginData.getPhotoUrl());
                        }
                    }
                });
                mIvUserIcon.setVisibility(View.VISIBLE);
                mTvLogout.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public void initShoppingItemNum() {

    }
}
